package com.katesoft.scale4j.rttp.jmx;

import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.rttp.internal.AppContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.ClassUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;

/** @author kate2007 */
@ManagedResource(objectName = IRttpSupportMBean.OBJ_RTTP_SUPPORT)
public class RttpSupportService implements IRttpSupportMBean
{
    private Logger logger = LogFactory.getLogger(getClass());

    @Override
    @ManagedOperation
    public void stopService()
    {
        final ApplicationContext applicationContext = AppContext.getApplicationContext();
        if (applicationContext != null) {
            if (applicationContext instanceof AbstractApplicationContext) {
                AbstractApplicationContext context = (AbstractApplicationContext) applicationContext;
                logger.info("destroying application context %s", context.getDisplayName());
                context.destroy();
                logger.info("context %s is no longer active", context);
            }
            else {
                throw new IllegalStateException(
                    String.format("context=%s is not instanceof AbstractApplicationContext, unable to destroy such context", applicationContext));
            }
        }
    }

    @Override
    @ManagedOperation
    public Collection<String> beanNamesForType(String clazz) throws ClassNotFoundException
    {
        return new ArrayList<String>(
            Arrays.asList(AppContext.getApplicationContext().getBeanNamesForType(ClassUtils.forName(clazz, ClassUtils.getDefaultClassLoader()))));
    }

    @Override
    @ManagedAttribute
    public Date getStartUpDate()
    {
        return new Date(AppContext.getApplicationContext().getStartupDate());
    }

    @Override
    @ManagedAttribute
    public int getBeanDefinitionCount()
    {
        return AppContext.getApplicationContext().getBeanDefinitionCount();
    }
}
